<?php

namespace app\admin\validate;

use think\Validate;

/**
 * 管理员登录验证
 */
class Index extends Validate
{
    // 验证规则
    protected $rule = [
        'username'       => 'require|length:3,20|regex:^[a-zA-Z0-9_\x80-\xff\s·]+$',
        'password'       => 'require|regex:^(?!.*[&<>"\'\n\r]).{6,32}$',
        'captcha_switch' => 'checkCaptcha:/^[0-9a-zA-Z][0-9a-zA-Z]{3,5}$/',
    ];

    protected $message = [
        'username.require' => '用户名不能为空!',
        'username.length'  => '用户名长度必须在3-20字符之间!',
        'username.regex'   => '用户名不能有特殊字符!',
        'password.require' => '密码不能为空!',
        'password.regex'   => '密码长度必须在6-32字符之间!',
    ];

    // 自定义验证规则
    protected function checkCaptcha($value, $rule, $data = [])
    {
        $captchaSwitch = $value; // 验证码是否开启
        $captcha       = $data['captcha'] ?? ''; // 验证码
        if ($captchaSwitch === '') {
            return true;
        }
        if ($captchaSwitch) {
            if (empty($captcha)) {
                return __('验证码不能为空!');
            } else if (!preg_match($rule, $captcha)) {
                return __('请输入正确的验证码!');
            }
        }
        return true;
    }

}
